﻿using Common.Communal;
using ERP.Domain.System;
using MediatR;
using SqlSugar;
using System.Api.Read.Applications.Commands.Posts;
using System.DTO;

namespace System.Api.Read.Applications.CommandHandlers.Posts
{
    /// <summary>
    ///     岗位查询命令处理程序
    /// </summary>
    public class PostQueryCommandHandler : IRequestHandler<PostQueryCommand, ApiResult<ApiPaging<PostDTO>>>
    {
        private readonly ISqlSugarClient sqlSugar;

        public PostQueryCommandHandler(ISqlSugarClient sqlSugar)
        {
            this.sqlSugar = sqlSugar;
        }

        /// <summary>
        /// 处理岗位查询命令
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回任务</returns>
        public Task<ApiResult<ApiPaging<PostDTO>>> Handle(PostQueryCommand request, CancellationToken cancellationToken)
        {
            ApiResult<ApiPaging<PostDTO>> result = new ApiResult<ApiPaging<PostDTO>>();
            var query = sqlSugar.Queryable<Post>().LeftJoin<Organize>((a, b) => a.OrganizeNo == b.OrganizeNo).Where((a, b) => a.IsDeleted == false).Select((a, b) => new PostDTO
            {
                Id = a.Id,
                PostNo = a.PostNo,
                PostName = a.PostName,
                OrganizeNo = a.OrganizeNo,
                OrganizeName = b.OrganizeName,
                IsDeleted = a.IsDeleted
            });
            if (!string.IsNullOrEmpty(request.PostNameNo))
            {
                query = query.Where(a => a.PostNo.Contains(request.PostNameNo) || a.PostName.Contains(request.PostNameNo));
            }
            if (!string.IsNullOrEmpty(request.OrganizeNo))
            {
                query = query.Where(a => a.OrganizeNo.Equals(request.OrganizeNo));
            }
            int count = query.Count();
            int page = (int)Math.Ceiling(count * 1.0 / request.Size);
            var res = query.OrderBy(a => a.Id).Skip((request.Index - 1) * request.Size).Take(request.Size);
            ApiPaging<PostDTO> paging = new ApiPaging<PostDTO>()
            {
                TotalCount = count,
                TotalPage = page,
                Data = res.ToList()
            };
            result.Success(paging, result.Message = "岗位查询成功");
            return Task.FromResult(result);
        }
    }
}
